/**
 * WeChatController
 *
 * @description :: Server-side logic for managing Wechats
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var crypto = require("crypto");
var decode = require('urldecode');
var request = require("request");
var util = require("util");
var Logger = require('pomelo-logger').getLogger('WeChat', 'production');

var WeChatClass = require("../classes/WeChatClass");
var WeChatConfig = require("../configs/WeChatConfig");
var WeChatAppConfig = require("../configs/WeChatAppConfig");

module.exports = {
  /**
   * api for wechat public account server verify
   *
   * @param {Object} req Http Request
   * @param {Object} res Http Response
   */
  verifyToken: function (req, res) {
    var signature = req.query.signature;
    var timestamp = req.query.timestamp;
    var nonce = req.query.nonce;
    var echostr = req.query.echostr;

    Logger.debug("verifyToken params [ %j ]", req.query);

    var token = "wechatgamecodeplantercom";
    var tmpArr = [token, timestamp, nonce];
    tmpArr.sort();
    var tmpStr = tmpArr.join().replace(/,/g, "");
    var sha1 = crypto.createHash('sha1');
    sha1.update(tmpStr);
    var tmpSha1Str = sha1.digest('hex');

    Logger.debug("verifyToken calc tmpArr [ %j ] tmpStr [ %s ] sha1 [ %s ] sig from wechat [ %s ]", tmpArr, tmpStr, tmpSha1Str, signature);

    if (tmpSha1Str == signature) {
      res.send(echostr);
    } else {
      res.end();
    }
  },

  /**
   * get cached auth data
   *
   * @param {Object} req Http Request
   * @param {Object} res Http Response
   */
  getAuthData: function (req, res) {
    var self = this;

    var appid = req.query.appid;
    if (!appid || appid.length != 18) {
      res.fail({"status": 10001001, "msg": "lack necessary params"});
      return;
    }

    WeChatAPIService.getCachedAccessToken(appid, function (err, info) {
      if (err) {
        res.fail(err);
      } else {
        res.json(new WeChatClass.InjectInfo(info));
      }
    });
  },

  /**
   * Hujiao App Share Web Link Callback URL
   *
   * @param {Object} req Http Request
   * @param {Object} res Http Response
   */
  huJiaoShare: function (req, res) {
    var self = this;

    function getClientIP(req) {
      var ipAddress;
      var headers = req.headers;
      var forwardedIpsStr = headers["x-real-ip"] || headers["x-forwarded-for"];
      forwardedIpsStr ? ipAddress = forwardedIpsStr : ipAddress = null;
      if (!ipAddress) {
        ipAddress = req.connection.remoteAddress;
      }
      return ipAddress;
    }

    var appid = WeChatAppConfig.HuJiao.appid;
    WeChatToken.findData(appid, function (err, info) {
      if (err || !info || !info.ip_list) {
        return self._huJiaoShare(req, res);
      }
      Logger.debug(info.ip_list, getClientIP(req));
      if (info.ip_list.indexOf(getClientIP(req)) == -1) {
        var newUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + req.originalUrl + '#wechat_redirect';
        res.redirect(newUrl);
      } else {
        return self._huJiaoShare(req, res);
      }
    });
  },
  _huJiaoShare: function (req, res) {
    res.locals.layout = "";
    // params
    var code = req.query.code || "";
    var state = req.query.state;
    var appid = WeChatAppConfig.HuJiao.appid;
    var redirect_url = WeChatAppConfig.HuJiao.url + req.url;

    // error message code list
    var ErrorMsg = {
      "ParamsNotValid": ["10001", "params not valid"],
      "LoadDataFromRemoteError": ["10002", "load data from remote error"]
    };

    // error message class
    function ErrorMessage(list) {
      this.errcode = list[0];
      this.errmsg = list[1];
    }

    function UnAuthPage(msgid, userid, pageinfo, res) {
      var data = {
        "msgid": msgid,
        "userid": userid,
        "shareinfo": WeChatAppConfig.HuJiao.share_link,
        "pageinfo": pageinfo,
        "authdata": null
      };
      Logger.debug("ret unauth page info [ %j ]", data);
      //res.json(data);
      //res.view("WeChatDemo/WeChatDemo", data);
      res.view("HuJiao/HuJiao", data);
    }

    function AuthPage(msgid, userid, pageinfo, authData, res) {
      var data = {
        "msgid": msgid,
        "userid": userid,
        "shareinfo": WeChatAppConfig.HuJiao.share_link,
        "pageinfo": pageinfo,
        "authdata": authData
      };
      Logger.debug("ret auth page info [ %j ]", data);
      //res.json(data);
      //res.view("WeChatDemo/WeChatDemo", data);
      res.view("HuJiao/HuJiao", data);
    }

    /**
     * 分享数据结构
     * @param info
     * @constructor
     */
    function PageInfo(info) {
      this.user_id = info.user_id;
      this.user_pic = info.user_pic;
      this.nick_name = info.nick_name;
      this.location = util.format("%,%", info.coor_lng, info.coor_lat);
      //this.coor_lng = info.coor_lng;
      //this.coor_lat = info.coor_lat;

      this.msg_id = info.msg_id;
      this.msg_type = info.msg_type;
      this.content_url = info.content_url;
      this.content_text = info.content_text;
      this.send_time = info.send_time;

      this.comment_list = [];
    }

    /**
     * 给分享添加评论
     * @param commentInfo
     */
    PageInfo.prototype.patchCommentList = function (commentInfo) {
      this.comment_list.push(new CommentInfo(commentInfo));
    };

    /**
     * 评论数据结构
     * @param info
     * @constructor
     */
    function CommentInfo(info) {
      this.comment_user_id = info.comment_user_id;
      this.comment_user_head_img = info.comment_user_head_img;
      this.comment_user_nick = info.comment_user_nick;
      this.comment_user_location = info.comment_user_location;

      this.comment_id = info.comment_id;
      this.msg_type = info.msg_type;
      this.content_url = info.content_url;
      this.content_text = info.content_text;
      this.create_time = info.create_time;
    }


    // parse state info
    var stateInfoList = state.split(",");
    var msgid = stateInfoList[0];
    var userid = stateInfoList[1];

    if (!msgid || !userid) {
      res.json(new ErrorMessage(ErrorMsg.ParamsNotValid));
      return;
    }

    // todo load data from server
    //var pageinfo = new PageInfo({
    //  "user_id": "1234567890",
    //  "nick_name": "HujiaoUser",
    //  "user_pic": "http://game.cocoplayer.com/HuJiao/data/profile/user.png",
    //  "coor_lng": 114.2347,
    //  "coor_lat": 45.2950,
    //
    //  "msg_id": "1000243356",
    //  "msg_type": "S",
    //  "content_url": "NdI4mjRKoNSUycaoIdAtsi4ZxsSETGaWKE-Geweo_OQnrM6MwZxOmskN8DzhNEMQ",
    //  "content_text": "",
    //  "send_time": "yyyy-MM-dd HH:mm:ss"
    //});
    //pageinfo.patchCommentList({
    //  "comment_id": "wertwytw443576534r543",
    //  "msg_type": "T",
    //  "content_url": "",
    //  "content_text": "赞, 你的声音很好听~O(∩_∩)O哈哈~",
    //  "create_time": "yyyy-MM-dd HH:mm:ss",
    //
    //  "comment_user_id": "2345678901",
    //  "comment_user_head_img": "http://game.cocoplayer.com/HuJiao/data/profile/avatar-1.png",
    //  "comment_user_nick": "大明湖畔的夏雨荷",
    //  "comment_user_location": "45.1265,144.6000"
    //});
    //pageinfo.patchCommentList({
    //  "comment_id": "wertwytw443576534r54w",
    //  "msg_type": "T",
    //  "content_url": "",
    //  "content_text": "2015年10月16日，辽宁省大连市现山寨版“威尼斯水城”。据悉，山寨版“威尼斯水城”为大连海昌东方" +
    //  "水城项目。项目占地面积40.36万平方米,规划建筑面积18.16万平方米。由法国设计师团队设计，斥资50亿元投资建设。图为" +
    //  "2015年10月16日，辽宁省大连市现山寨版“威尼斯水城”。" +
    //  "电动平衡车是一种新兴的交通工具，时尚青年们驾驶着电动平衡车从城市的街道上掠过，颇能吸引路人的目光。不过最近一位" +
    //  "名叫劳伦的女子借着平衡车更是好好的炒作了一下，她全身裸体驾驶某品牌的电动平衡车在城市的街道、公园、十字路口穿行，" +
    //  "成功吸引了无数路人的目光。",
    //  "create_time": "yyyy-MM-dd HH:mm:ss",
    //
    //  "comment_user_id": "2345678902",
    //  "comment_user_head_img": "http://game.cocoplayer.com/HuJiao/data/profile/avatar-2.png",
    //  "comment_user_nick": "☆私は♂淍菭荢↘",
    //  "comment_user_location": "45.1265,144.6000"
    //});
    //pageinfo.patchCommentList({
    //  "comment_id": "wertwytw443576534r5uw",
    //  "msg_type": "S",
    //  "content_url": "bZ5a0s5gstMEu86e-TqpW4ABn1yxiecwJ2LAywTAvHj48eSEI0xiz4eVfl0db2KP",
    //  "content_text": "",
    //  "create_time": "yyyy-MM-dd HH:mm:ss",
    //
    //  "comment_user_id": "2345678903",
    //  "comment_user_head_img": "http://game.cocoplayer.com/HuJiao/data/profile/avatar-2.png",
    //  "comment_user_nick": "猴子请来的救兵",
    //  "comment_user_location": "35.1265,134.6000"
    //});

    if (!code) {
      // user did't auth, hide comment div
      new UnAuthPage(msgid, userid, pageinfo, res);
      return;
    }

    request("http://game.cocoplayer.com:1337/HuJiaoShare/loadData?msg_id=" + msgid, function (err, response, body) {
      if (!err && response.statusCode == 200) {
        var msg = {};
        try {
          msg = JSON.parse(body);
        } catch (e) {
          Logger.error("Parse Data From Remote List Error [ %s ]", body);
          res.json(new ErrorMessage(ErrorMsg.LoadDataFromRemoteError));
          return;
        }

        var pageinfo = new PageInfo(msg);
        var commentList = msg.comment_list || [];
        for (var i = 0; i < commentList.length; i++) {
          pageinfo.patchCommentList(new CommentInfo(commentList[i]));
        }

        // user auth
        var WebTokenAuthId = util.format("%s:%s", "HuJiao", userid);
        WeChatAPIService.requestWebAccessToken(appid, WeChatConfig[appid].secret, code, userid, function (err, msg) {
          /**
           * msg:
           * "access_token":"ACCESS_TOKEN",
           * "expires_in":7200,
           * "refresh_token":"REFRESH_TOKEN",
           * "openid":"OPENID",
           * "scope":"SCOPE",
           * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
           */
          if (err || !msg.access_token || !msg.openid) {
            return new UnAuthPage(appid, userid, pageinfo, res);
          }
          WeChatAPIService.requestUserInfo(msg.access_token, msg.openid, userid, function (err, msg) {
            /**
             * msg:
             * "openid":"OPENID",
             * "nickname": "NICKNAME",
             * "sex":"1",
             * "province":"PROVINCE"
             * "city":"CITY",
             * "country":"COUNTRY",
             * "headimgurl":"http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
             * "privilege":[
             *     "PRIVILEGE1"
             *     "PRIVILEGE2"
             *  ],
             * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
             */
            if (err || !msg.openid || !msg.nickname || !msg.headimgurl) {
              return new UnAuthPage(appid, userid, pageinfo, res);
            }
            WeChatAPIService.getCachedAccessToken(appid, function (err, info) {
              if (err || !info.access_token || !info.jsapi_ticket) {
                return new UnAuthPage(appid, userid, pageinfo, res);
              }

              var authData = {
                "userInfo": {
                  "openid": msg.openid,
                  "nickname": msg.nickname,
                  "headimgurl": msg.headimgurl
                },
                "appInfo": {
                  "appid": appid,
                  "access_token": info.access_token,
                  "jsapi_ticket": info.jsapi_ticket
                },
                "injectInfo": WeChatAPIService.calcSignature(info.jsapi_ticket, redirect_url)
              };
              return new AuthPage(msgid, userid, pageinfo, authData, res);
            });
          });
        });
      } else {
        Logger.error("Load Data From Remote Error [ %s ] [ %s ]", response.statusCode, body, err);
        res.json(new ErrorMessage(ErrorMsg.LoadDataFromRemoteError));
      }
    });
  }
};

